var Msdb = require('./db/Msdb.js')
const fetch = require('node-fetch');
const { saveczlog_util } = require('./routes/adminroute/qb/server_util');
const { logger } = require('./logger.js');


/**通用请求 fetchsync_util
 * url 地址, type 类型[POST/GET], param 值, rttype  返回类型
 */
async function fetchsync_util(url, type, param, rttype, Authorization) {
    return new Promise(function (resolve, reject) {
        fetch(url, {
            method: type,
            mode: 'cors',
            // credentials: 'include',
            headers: {
                'Content-Type': 'application/json;charset=UTF-8',
                'Authorization': Authorization
            },
            body: JSON.stringify(param)
        }
        ).then(response => {

            return rttype == "json" ? response.json() : response.text();
        }).then(data => {
            resolve(data)

        });

    })
}

//获取token
const getToken = async () => {
    let Authorization = 'Basic ZjhmMmJhOWUtYzNjMC00NmFmLWEzNzItNjk3MWFiMDZmY2QwOjc0Mjg1NjBlLTc4MzItNGU1OC1iOWNjLWYwZWUxNjI2YzQyZQ=='
    let url = 'https://openapi.ihr360.com/openapi/oauth/token?grant_type=client_credentials&scope=client'
    let result = await fetchsync_util(url, 'POST', {}, "json", Authorization)
    return result;
}

//刷新token
const refreshToken = async () => {
    let tokenResult = await getToken()
    // console.log(tokenResult.refresh_token);
    let Authorization = 'Basic ZjhmMmJhOWUtYzNjMC00NmFmLWEzNzItNjk3MWFiMDZmY2QwOjc0Mjg1NjBlLTc4MzItNGU1OC1iOWNjLWYwZWUxNjI2YzQyZQ=='
    let url = `https://openapi.ihr360.com/openapi/oauth/token?grant_type=refresh_token&refresh_token=${tokenResult.refresh_token}`
    // let param={grant_type:'refresh_token',refresh_token:tokenResult.refresh_token}
    let result = await fetchsync_util(url, 'POST', {}, "json", Authorization)
    // console.log("刷新的token对象",result);
    return result;
}

//获取所有员工ID清单
async function ygdaSync() {
    return new Promise(async (resolve, reject) => {

        let ids = []
        let tokenResult = await getToken()
        let url = 'https://openapi.ihr360.com/openapi/thirdparty/api/staff/v1/staffs/ids?pageNo=1'
        let Authorization = 'Bearer ' + tokenResult.access_token
        let result = await fetchsync_util(url, 'GET', {}, "json", Authorization)
        console.log(result.data.pageInfo.totalPages, "总页数");
        for (let i = 1; i <= result.data.pageInfo.totalPages; i++) {
            let url = `https://openapi.ihr360.com/openapi/thirdparty/api/staff/v1/staffs/ids?pageNo=${i}`
            let result2 = await fetchsync_util(url, 'GET', {}, "json", Authorization)
            ids = ids.concat(result2.data.dataList)
            console.log(i, result2.data.dataList.length);
        }
        console.log("员工ID清单", ids.length);
        await getBatchInfo(ids)
        await refreshToken()
        resolve(1)
    })
}

//批量获取员工基本信息
const getBatchInfo = async (ids) => {

    let url = 'https://openapi.ihr360.com/openapi/thirdparty/api/staff/v1/staffs/basic'
    let tokenResult = await getToken()
    let Authorization = 'Bearer ' + tokenResult.access_token
    let result = await fetchsync_util(url, 'POST', ids, "json", Authorization)
    let quitResult = result.data.filter(item => item.staffStatus == "QUIT" && item.staffNo !== null && item.staffNo.length === 6)
    let zzResult = result.data.filter(item => item.staffStatus != "QUIT")
    await quitSync(quitResult)
    await zzSync(zzResult)
    await refreshToken()
}

//处理离职员工函数
const quitSync = async (quitResult) => {
    var db = new Msdb()
    let ygxmString = ""
    for (let i = 0; i < quitResult.length; i++) {
        var sql = `update qb_ygda set jyzt='B' where ygbh='${quitResult[i].staffNo}'`
        await db.update(sql)
        ygxmString += ` ${quitResult[i].staffNo}-${quitResult[i].staffName} `
    }
    let storage = { ygxm: 'admin', ygbh: '1' }
    console.log(ygxmString, "离职");
    await saveczlog_util(ygxmString, storage, '', "更新离职人员禁用状态", "更新", "qb_ygda")
}
//处理正式员工函数
const zzSync = async (zzResult) => {
    var db = new Msdb()
    var sql = `select * from qb_ygda`
    var result = await db.query(sql)

    let ygxmString = ""
    for (let i = 0; i < zzResult.length; i++) {
        let ygResult = await getYgInfo(zzResult[i].staffId)
        // let ygResult = zzResult[i]
        if (!result.recordsets[0].some(item => item.ygbh == ygResult.staffNo)) {
            var sql = `insert into qb_ygda(id,create_time,create_by,gw,ygbh,ygxm,dh,jyzt,sex,department,zz,username,password,companyid,staffType)values('${ygResult.id}',getdate(),'admin',
            '${ygResult.positionName}','${ygResult.staffNo}','${ygResult.staffName}','${ygResult.mobileNo}','A',
            '${ygResult.sex == "MALE" ? "男" : "女"}','${ygResult.departmentName}','${ygResult.fullDepartmentName.split('/')[0]}','${ygResult.staffNo}','123456','${ygResult.companyId}','${ygResult.staffType}')`
            await db.update(sql)
            ygxmString += `新增人员${ygResult.staffNo}-${ygResult.staffName} `
        }
        else {
            var sql = `update qb_ygda set department='${ygResult.departmentName}',zz='${ygResult.fullDepartmentName.split('/')[0]}',sex='${ygResult.sex == "MALE" ? "男" : "女"}',
            gw='${ygResult.positionName}',companyid='${ygResult.companyId}',staffType='${ygResult.staffType}' where ygbh='${ygResult.staffNo}'`
            await db.update(sql)
            ygxmString += `更新人员${ygResult.staffNo}-${ygResult.staffName} `
        }
    }
    await db.update(`update qb_ygda set stafftype='全职' WHERE  stafftype='FULLTIME'`)
    await db.update(`update qb_ygda set stafftype='兼职' WHERE  stafftype='PARTTIME'`)
    await db.update(`update qb_ygda set stafftype='实习' WHERE  stafftype='INTERSHIP'`)
    await db.update(`update qb_ygda set stafftype='外派' WHERE  stafftype='EXPATRIATE'`)
    await db.update(`update qb_ygda set stafftype='临时工' WHERE  stafftype='TEMPORARY'`)
    await db.update(`update qb_ygda set stafftype='退休返聘' WHERE  stafftype='REHIRE_RETIREMENT'`)
    console.log(ygxmString, "在职");
    let storage = { ygxm: 'admin', ygbh: '1' }
    await saveczlog_util(ygxmString, storage, '', "新增和更新人员", "新增和更新", "qb_ygda")
}

//获取员工信息详情V2
const getYgInfo = async (id) => {
    let tokenResult = await getToken()
    let url = `https://openapi.ihr360.com/openapi/thirdparty/api/staff/v1/staffs/${id}/superiors/detail`
    let Authorization = 'Bearer' + tokenResult.access_token
    let result = await fetchsync_util(url, 'GET', {}, "json", Authorization)
    return result.data
}

// //同步IHR部门
const bmSync = async () => {
    return new Promise(async (resolve, reject) => {
        let tokenResult = await getToken()
        let url = 'https://openapi.ihr360.com/openapi/thirdparty/api/org/v2/companies/organizations'
        let Authorization = 'Bearer ' + tokenResult.access_token
        let result = await fetchsync_util(url, 'GET', {}, "json", Authorization)
        let ihrList = result.data
        console.log(ihrList[0]);
        var db = new Msdb()
        var sql = `select * from qb_ihr_bm`
        var bmResult = await db.query(sql)
        let ygxmString = ""
        for (let i = 0; i < ihrList.length; i++) {
            for (let key in ihrList[i]) {
                if (ihrList[i][key] === null) {
                    ihrList[i][key] = "";
                }
            }
            if (!bmResult.recordsets[0].some(item => item.id == ihrList[i].id)) {
                var sql = `insert into qb_ihr_bm(id,name,create_time,create_by,parentld,type,departmentCode, principalStaffld,parentDepartmentCode
                ,departmentStatus,departmentDesc)  values('${ihrList[i].id}','${ihrList[i].name}',getdate(),'admin',
                '${ihrList[i].parentId}','${ihrList[i].type}','${ihrList[i].departmentCode}','${ihrList[i].principalStaffId}',
                '${ihrList[i].parentDepartmentCode}','${ihrList[i].departmentStatus}','${ihrList[i].departmentDesc}')`
                await db.update(sql)
                ygxmString += `新增部门${ihrList[i].name}`
            }
            else {
                var sql = `update qb_ihr_bm set name='${ihrList[i].name}',parentld='${ihrList[i].parentId}',type='${ihrList[i].type}'
                ,departmentCode='${ihrList[i].departmentCode}',principalStaffld='${ihrList[i].principalStaffId}',parentDepartmentCode='${ihrList[i].parentDepartmentCode}'
                ,departmentStatus='${ihrList[i].departmentStatus}',departmentDesc='${ihrList[i].departmentDesc}'
                where id='${ihrList[i].id}'`
                await db.update(sql)
                ygxmString += `更新部门${ihrList[i].name}`
            }
        }

        console.log(result.data.length);
        let storage = { ygxm: 'admin', ygbh: '1' }
        await saveczlog_util(ygxmString, storage, '', "新增和更新部门", "新增和更新", "qb_ihr_bm")
    })
}
// bmSync()
// ygdaSync()


module.exports = {
    ygdaSync,
    bmSync
};